import drawQrcode from "../../utils/weapp.qrcode.js"
import { showErrorToast, showSuccessToast } from "../../utils/toast"

type recordT = {
  image: string,
  text: string,
}

// pages/text_qrcode/qrcode.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    text: '',
    current: {image: '', text: ''},
    historyKey: 'text-qrcode-history',
    history: [] as recordT[],
    popVisible: false,
    popImageShow: false,
    popCavasShow: true,
  },

  onClearText() {
    this.setData({
      text: '',
    })
  },

  onTextChange(e: WechatMiniprogram.CustomEvent) {
    let { value } = e.detail
    this.data.text = value
  },

  onDrawQrcode() {
    console.log(this.data.text)
    if (!this.data.text) {
      showErrorToast(this, '请选输入URL')
      return;
    }
    this.setData({
      current: {text: this.data.text, image: ''},
      popVisible: true,
      popCavasShow: true,
      popImageShow: false,
    })
    wx.nextTick(() => {
      this.drawQrcode()
    })
  },

  drawQrcode() {
    let draw = new Promise<boolean>((resolve) => {
      drawQrcode({
        width: 200,
        height: 200,
        canvasId: 'myQrcode',
        // ctx: wx.createCanvasContext('myQrcode'),
        callback: () => {
          resolve(true)
        },
        text: this.data.current.text,
        // v1.0.0+版本支持在二维码上绘制图片
        // image: {
        //   imageResource: '../../images/icon.png',
        //   dx: 70,
        //   dy: 70,
        //   dWidth: 60,
        //   dHeight: 60
        // }
      })
    })

    draw.then(() => {
      wx.canvasToTempFilePath({
        canvasId: 'myQrcode',
        x: 10,
        y: 10,
        width: 220,
        height: 220,
        destWidth: 200,
        destHeight: 200,
        success: (res) => {
            console.log('二维码临时路径：', res.tempFilePath)
            let history = this.data.history
            let current = this.data.current
  
            current.image = res.tempFilePath
            history.unshift(current)
            
            this.setData({
              current: current,
              history: history,
            })
            this.appendHistoryRecord(current)
        },
        fail: (res) => {
          console.log('临时路径错误：', res)
          showErrorToast(this, `获取图片地址失败 ${res}`)
        }
      }, this)
    }).catch((e) => {
      console.log(e)
    })
  },

  // 追加新的历史记录，忽略错误信息
  appendHistoryRecord(result: recordT) {
    let append = (data: recordT[]) => {
      data.unshift(result)
      wx.setStorage({
        key: this.data.historyKey,
        data: data,
      })
    }
    wx.getStorage({
      key: this.data.historyKey,
      success:  (res) => {
        let data = res.data as recordT[]  || []
        append(data)
      },
      fail: () => {
        append([])
      }
    })
  },

  onClearHistory() {
    wx.setStorage({
      key: this.data.historyKey,
      data: [],
      success: () => {
        this.setData({
          current: {image: '', text: ''},
          history: [],
        })
        showSuccessToast(this, '历史记录已清空')
      },
      fail: (e) => {
        showErrorToast(this, `清除历史记录失败 ${e}`)
      }
    })
  },

  onVisibleChange() {
    this.setData({
      popVisible: false,
    })
  },

  onPopShow(e: WechatMiniprogram.CustomEvent) {
    let { item } = e.currentTarget.dataset
    if (!item || !item['image']) {
      showErrorToast(this, '数据错误')
      return
    }

    this.setData({
      current: item,
      popVisible: true,
      popImageShow: true,
      popCavasShow: false,
    })
  },

  onResultSave() {
    if (!this.data.current.image) {
      showErrorToast(this, '未找到图片')
      return
    }
    wx.saveImageToPhotosAlbum({
      filePath: this.data.current.image,
      success: () => {
        showSuccessToast(this, '保存成功')
      },
      fail: () => {
        showErrorToast(this, '保存失败')
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.getStorage({
      key: this.data.historyKey,
      success: (res) => {
        let data = res.data as recordT[]
        if (!data) {
          return
        }

        this.setData({
          history: data,
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})